#!/bin/bash
#本脚本适用于CentOS7的k8s预初始化
# 2021-06-19
# 时区为上海时间
TimeZone='Asia/Shanghai'


#关闭防火墙
systemctl disable firewalld && systemctl stop firewalld

#关闭selinux
setenforce 0
#永久关闭
sed -i "s/SELINUX=enforcing/SELINUX=disabled/" /etc/sysconfig/selinux
sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config

# 修改所有的用户默认可以打开最大的进程数为 40960
sed -i 's/\*.*soft.*nproc.*4096$/&0/' /etc/security/limits.d/20-nproc.conf 

# 修改最大链接数
ulimit -n 65535
echo '
* soft nofile 65535
* hard nofile 65535
' >> /etc/security/limits.conf

#禁用swap
swapoff -a
#永久禁用
sed -i "s/.*swap.*/#&/" /etc/fstab

#关闭NUMA，升级4.4内核时才执行
#sed -i 's/GRUB_CMDLINE_LINUX=\"/&numa=off /g' /etc/default/grub

#Kernel参数修改
cat <<EOF >  /etc/sysctl.d/k8s.conf

#要求iptables对bridge的数据进行处理
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1

#Kernel性能调优
net.ipv4.ip_forward=1
net.bridge.bridge-nf-call-iptables=1
net.ipv4.neigh.default.gc_thresh1=4096
net.ipv4.neigh.default.gc_thresh2=6144
net.ipv4.neigh.default.gc_thresh3=8192

net.ipv4.tcp_tw_recycle=0
vm.swappiness=0 # 禁止使用 swap 空间，只有当系统 OOM 时才允许使用它
vm.overcommit_memory=1 # 不检查物理内存是否够用
vm.panic_on_oom=0 # 开启 OOM
fs.inotify.max_user_instances=8192
fs.inotify.max_user_watches=1048576
fs.file-max=52706963
fs.nr_open=52706963
net.ipv6.conf.all.disable_ipv6=1
net.netfilter.nf_conntrack_max=2310720
EOF


#重新加载配置文件
sysctl -p /etc/sysctl.d/kubernetes.conf
#sysctl --system

#配置阿里k8s yum源
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64/
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg https://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

#更新yum缓存，并安装epel
yum install -y epel-release
yum clean all -y && yum makecache -y && yum repolist -y

#设置时间服务器并同步时间
yum install ntp -y
systemctl enable ntpd && systemctl start ntpd
cp -rf /etc/localtime /etc/localtime
ln -sf /usr/share/zoneinfo/${TimeZone} /etc/localtime
# 将当前的 UTC 时间写入硬件时钟
timedatectl set-local-rtc 0

#关闭不必要服务
systemctl stop postfix && systemctl disable postfix


#安装运维常用调优工具(可选)
yum install -y  net-tools iftop htop iotop atop \
                nmon nmap \
                vnstat sysstat nethogs \
                vim zip unzip lrzsz lsof wget time  \
                smart smartmontools hdparm fio strace \
                telnet expect \
                autoconf bridge-utils \
                conntrack ipvsadm ipset jq iptables curl sysstat libseccomp wget vim net-tools git tee


#安装ipvs
modprobe br_netfilter
cat > /etc/sysconfig/modules/ipvs.modules <<EOF
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack_ipv4
EOF
chmod 755 /etc/sysconfig/modules/ipvs.modules && \
bash /etc/sysconfig/modules/ipvs.modules && \
lsmod | grep -e ip_vs -e nf_conntrack_ipv4